package com.huayi.order.repository;


import com.huayi.order.controller.OrderSendReq;
import com.huayi.order.entity.*;
import com.huayi.order.enums.EnumErpOrderStatus;
import com.huayi.order.thymeleaf.PagingResponse;
import com.huayi.order.utils.DateUtil;
import com.huayi.order.utils.EnumResultVo;
import com.huayi.order.utils.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

/**
 * 销售外发订单
 */
@Repository
public class ErpSalesOrderRepository {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 查询总页数
     *
     * @return
     */
    protected int getTotalSize() {
        return jdbcTemplate.queryForObject("SELECT FOUND_ROWS() as row_num;", int.class);
    }

    public ErpSalesOrderEntity getById(Long orderId) {
        try {
            return jdbcTemplate.queryForObject("SELECT * FROM " + Tables.SalesOrder + " WHERE id=?", new BeanPropertyRowMapper<>(ErpSalesOrderEntity.class), orderId);
        } catch (Exception e) {
            return null;
        }
    }

    @Transactional
    public PagingResponse<ErpSalesOrderDetailVo> getList(int pageIndex, int pageSize, String orderNum, String contactMobile, Integer saleType, Integer status, Integer startTime, Integer endTime,Integer salesManId) {
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT SQL_CALC_FOUND_ROWS o.*");
        sb.append(" FROM ").append(Tables.SalesOrder).append(" as o ");
//        sb.append(" LEFT JOIN ").append(Tables.DcShop).append(" as shop on shop.id = o.shopId ");
//        sb.append(" LEFT JOIN ").append(Tables.User).append(" as dev on dev.id = o.developerId ");
        sb.append(" WHERE 1=1 ");

        List<Object> params = new ArrayList<>();

        if (saleType != null && saleType>=0) {
            sb.append(" AND o.saleType=? ");
            params.add(saleType);
        }

        if (status != null) {
            sb.append(" AND o.status=? ");
            params.add(status);
        }
        if (startTime != null && startTime > 0) {
            sb.append(" AND o.createOn >= ? ");
            params.add(startTime);
        }
        if (endTime != null && endTime > 0) {
            sb.append(" AND o.createOn <= ? ");
            params.add(endTime);
        }
        if (StringUtils.isEmpty(orderNum) == false) {
            sb.append(" AND o.orderNum=? ");
            params.add(orderNum);
        }

        if (StringUtils.isEmpty(contactMobile) == false) {
            sb.append(" AND o.contactMobile=? ");
            params.add(contactMobile);
        }
        if (salesManId != null && salesManId > 0) {
            sb.append(" AND o.salesManId = ? ");
            params.add(salesManId);
        }
        sb.append(" ORDER BY o.id DESC LIMIT ?,? ");
        params.add((pageIndex - 1) * pageSize);
        params.add(pageSize);
        List<ErpSalesOrderDetailVo> list = jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(ErpSalesOrderDetailVo.class), params.toArray(new Object[params.size()]));
        int totalSize = getTotalSize();
        for (ErpSalesOrderDetailVo item:list) {
            item.setItems(jdbcTemplate.query("SELECT * FROM "+Tables.SalesOrderItem+" WHERE orderId=?",new BeanPropertyRowMapper<>(ErpSalesOrderItemEntity.class),item.getId()));
        }
        return new PagingResponse<>(pageIndex, pageSize, totalSize, list);
    }

    @Transactional
    public List<ErpSalesOrderItemVo> getOrderItemListAll(String orderNum, String contactMobile, Integer saleType, Integer status, Integer startTime, Integer endTime) {
        StringBuilder sb = new StringBuilder();
        sb.append("SELECT oi.*,o.orderDate,o.orderNum,o.contactPerson,o.contactMobile,o.address,o.logisticsCompany,o.logisticsCode");
        sb.append(",o.payStatus,o.payMethod,o.deliveredStatus,o.deliveredTime,o.sellerMemo,o.shippingFee,o.saleType,o.status ");
        sb.append(",sm.true_name as salesMan");
        sb.append(" FROM ").append(Tables.SalesOrderItem).append(" as oi ");
        sb.append(" LEFT JOIN ").append(Tables.SalesOrder).append(" as o on o.id = oi.orderId ");
        sb.append(" LEFT JOIN hy_sales_man").append(" as sm on sm.id = o.salesManId ");

        sb.append(" WHERE 1=1 ");

        List<Object> params = new ArrayList<>();

        if (saleType != null && saleType>=0) {
            sb.append(" AND o.saleType=? ");
            params.add(saleType);
        }

        if (status != null) {
            sb.append(" AND o.status=? ");
            params.add(status);
        }
        if (startTime != null && startTime > 0) {
            sb.append(" AND o.createOn >= ? ");
            params.add(startTime);
        }
        if (endTime != null && endTime > 0) {
            sb.append(" AND o.createOn <= ? ");
            params.add(endTime);
        }
        if (StringUtils.isEmpty(orderNum) == false) {
            sb.append(" AND o.orderNum=? ");
            params.add(orderNum);
        }

        if (StringUtils.isEmpty(contactMobile) == false) {
            sb.append(" AND o.contactMobile=? ");
            params.add(contactMobile);
        }

        sb.append(" ORDER BY o.id DESC  ");

        List<ErpSalesOrderItemVo> list = jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<>(ErpSalesOrderItemVo.class), params.toArray(new Object[params.size()]));
        return list;
    }

    /**
     * 导入代发订单
     *
     * @param orderList
     * @param buyerUserId
     * @return
     */
    @Transactional
    public ResultVo<String> importExcelOrderForDaiFa(List<OrderImportDaiFaEntity> orderList, Integer buyerUserId) {
        if (orderList == null || orderList.size() == 0)
            return new ResultVo<>(EnumResultVo.DataError, "参数错误：缺少orderList","");
        if (buyerUserId == null || buyerUserId == 0)
            return new ResultVo<>(EnumResultVo.DataError, "参数错误：缺少buyerUserId","");



        /*******插入数据********/
        int totalInsert = 0;//新增数量
        int totalExist = 0;//已存在数量
        int totalError = 0;//错误数量
        for (OrderImportDaiFaEntity order : orderList) {
            //查询订单是否存在
            List<OrderImportDaiFaEntity> oList = jdbcTemplate.query("SELECT * FROM " + Tables.SalesOrder + " WHERE orderNum=? ", new BeanPropertyRowMapper<>(OrderImportDaiFaEntity.class), order.getId());

            if (oList != null && oList.size() > 0) {
                //已经存在
                totalExist++;
            } else {

                try {
                    /**************1、新增order**********************/
                    //商品总价
                    double goodsTotalAmount = 0.0;
                    //商品总数
                    long goodsCount = 0;
                    //sku总数
                    long goodsSpecCount = 0;

                    for (OrderImportItem item : order.getItems()) {
                        goodsCount += item.getQuantity();
                        goodsSpecCount++;
                        goodsTotalAmount += item.getPrice().doubleValue() * item.getQuantity();
                    }
                    //销售类型为实售
                    int saleType = 1;
                    //订单状态为待发货
                    int status = EnumErpOrderStatus.WaitSend.getIndex();

                    StringBuilder insertSQL = new StringBuilder();
                    insertSQL.append("INSERT INTO ").append(Tables.SalesOrder);
                    insertSQL.append(" (orderNum,buyerUserId,buyerName,goodsCount,goodsSpecCount,goodsTotalAmount,shippingFee,totalAmount,buyerFeedback,sellerMemo,contactPerson,contactMobile,province,city,area,address," +
                            "saleType,status,createOn,createBy,modifyOn,developerId,source,orderTime,billMethod)");
                    insertSQL.append(" VALUE (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,1) ");

                    KeyHolder keyHolder = new GeneratedKeyHolder();

                    long finalGoodsSpecCount = goodsSpecCount;
                    long finalGoodsCount = goodsCount;
                    double finalGoodsTotalAmount = goodsTotalAmount;
                    jdbcTemplate.update(new PreparedStatementCreator() {
                        @Override
                        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                            PreparedStatement ps = connection.prepareStatement(insertSQL.toString(), Statement.RETURN_GENERATED_KEYS);
                            ps.setString(1, order.getId());
                            ps.setInt(2, buyerUserId);
                            ps.setString(3, "");
                            ps.setLong(4, finalGoodsCount);
                            ps.setLong(5, finalGoodsSpecCount);
                            ps.setBigDecimal(6, new BigDecimal(finalGoodsTotalAmount));
                            ps.setBigDecimal(7, new BigDecimal(0));
                            ps.setBigDecimal(8, new BigDecimal(finalGoodsTotalAmount));
                            ps.setString(9, order.getBuyerFeedback());
                            ps.setString(10, order.getSellerMemo());
                            ps.setString(11, order.getContactPerson());
                            ps.setString(12, order.getContactMobile());
                            ps.setString(13, order.getProvince() != null ? order.getProvince() : "");
                            ps.setString(14, order.getCity() != null ? order.getCity() : "");
                            ps.setString(15, order.getArea() != null ? order.getArea() : "");
                            ps.setString(16, order.getAddress() != null ? order.getAddress() : "");
                            ps.setInt(17, saleType);
                            ps.setInt(18, status);
                            ps.setLong(19, System.currentTimeMillis() / 1000);
                            ps.setString(20, "OMS-import-DaiFa");
                            ps.setLong(21, System.currentTimeMillis() / 1000);
                            ps.setInt(22, 0);
                            ps.setString(23, "DaiFaImport");
                            ps.setLong(24, DateUtil.dateToStamp(order.getOrderTime()));
                            return ps;
                        }
                    }, keyHolder);

                    Long orderId = keyHolder.getKey().longValue();

                    /*******************2、添加order_item**************************/
                    //添加订单明细
                    String itemSQL = "INSERT INTO " + Tables.SalesOrderItem + " (orderId,itemAmount,goodsId,goodsTitle,goodsNumber,goodsImage,skuInfo,specId,specNumber,color,size,price,quantity,discountPrice) VALUE (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                    for (OrderImportItem item : order.getItems()) {
                        double itemAmount = item.getPrice().doubleValue() * item.getQuantity();
                        jdbcTemplate.update(itemSQL, orderId, itemAmount, item.getGoodsId(), item.getGoodsTitle(), item.getGoodsNumber(), item.getGoodsImg(),
                                item.getSkuInfo(), item.getSpecId() == null ? 0 : item.getSpecId(), item.getSpecNumber(), item.getColor(), item.getSize(), item.getPrice(), item.getQuantity(), 0);
                    }

                    totalInsert++;//新增成功

                } catch (Exception e) {
                    totalError++;
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return new ResultVo<>(EnumResultVo.SystemException, "系统异常：" + e.getMessage(),"");
                }
            }
        }
        String msg = "新增成功：" + totalInsert + "，新增失败：" + totalError + "，已存在：" + totalExist;
////        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return new ResultVo<>(EnumResultVo.SUCCESS, "SUCCESS", msg);
//    }
    }


    public ErpSalesOrderDetailVo getDetailById(Long orderId) {
        try {
            String detailSQL = "SELECT o.* FROM " + Tables.SalesOrder + " AS o  WHERE o.id=?";
            ErpSalesOrderDetailVo order = jdbcTemplate.queryForObject(detailSQL, new BeanPropertyRowMapper<>(ErpSalesOrderDetailVo.class), orderId);

            order.setItems(jdbcTemplate.query("SELECT * FROM " + Tables.SalesOrderItem + " WHERE orderId=?", new BeanPropertyRowMapper<>(ErpSalesOrderItemEntity.class), orderId));
            return order;
        } catch (Exception e) {
            return null;
        }
    }

    public ErpSalesOrderItemEntity getOrderItemByItemId(Long orderItemId) {
        try {
            String detailSQL = "SELECT * FROM " + Tables.SalesOrderItem + " WHERE id=?";
            return jdbcTemplate.queryForObject(detailSQL, new BeanPropertyRowMapper<>(ErpSalesOrderItemEntity.class), orderItemId);
        } catch (Exception e) {
            return null;
        }

    }


    /**
     * 系统下单
     * @param salesOrder
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public ResultVo<Integer> editSalesOrder(ErpSalesOrderDetailVo salesOrder) {
        Long salesOrderId = 0L;//jdbcTemplate.queryForObject("SELECT IFNULL((SELECT id from erp_sales_order where orderNum=? ),0) id",Long.class,salesOrder.getOrderNum());

        StringBuilder insertSQL = new StringBuilder();
        if (salesOrder.getId() != null && salesOrder.getId() > 0) {
            //修改
            var order = jdbcTemplate.queryForObject("SELECT * FROM " + Tables.SalesOrder + " WHERE id=?", new BeanPropertyRowMapper<>(ErpSalesOrderEntity.class), salesOrder.getId());
            salesOrder.setOrderNum(order.getOrderNum());
            salesOrderId = salesOrder.getId();

            insertSQL.append("UPDATE ").append(Tables.SalesOrder);
        } else {
            //新增
            insertSQL.append("INSERT INTO ").append(Tables.SalesOrder);
        }

        insertSQL.append(" set  orderNum=?,");
        insertSQL.append(" goodsTotalAmount=?,");
        insertSQL.append(" shippingFee=?,");
        insertSQL.append(" totalAmount=?,");
        insertSQL.append(" contactPerson=?,");
        insertSQL.append(" contactMobile=?,");
        insertSQL.append(" province=?,");
        insertSQL.append(" city=?,");
        insertSQL.append(" area=?,");
        insertSQL.append(" address=?,");
        insertSQL.append(" saleType=?,");
        insertSQL.append(" status=?,");
        insertSQL.append(" createBy=?,");
        insertSQL.append(" source=?,");
        insertSQL.append(" payMethod=?,");
        insertSQL.append(" payStatus=?,");
        insertSQL.append(" payTime=?,");
        insertSQL.append(" payAmount=?,");
        if (salesOrder.getId() != null && salesOrder.getId() > 0) {
            //修改
            insertSQL.append(" sellerMemo=? ");
            insertSQL.append(" WHERE id=? ");
        } else {
            //新增
            insertSQL.append(" orderDate=?,");
            insertSQL.append(" createOn=?, ");
            insertSQL.append(" sellerMemo=?, ");
            insertSQL.append(" salesManId=? ");
        }


        try {
            if (salesOrderId.longValue() == 0) {
                KeyHolder keyHolder = new GeneratedKeyHolder();
                jdbcTemplate.update(new PreparedStatementCreator() {
                    @Override
                    public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                        PreparedStatement ps = connection.prepareStatement(insertSQL.toString(), Statement.RETURN_GENERATED_KEYS);
                        ps.setString(1, salesOrder.getOrderNum());
                        ps.setBigDecimal(2, salesOrder.getGoodsTotalAmount());
                        ps.setBigDecimal(3, salesOrder.getShippingFee());
                        ps.setBigDecimal(4, salesOrder.getTotalAmount());
                        ps.setString(5, salesOrder.getContactPerson());
                        ps.setString(6, salesOrder.getContactMobile());
                        ps.setString(7, salesOrder.getProvince());
                        ps.setString(8, salesOrder.getCity());
                        ps.setString(9, salesOrder.getArea());
                        ps.setString(10, salesOrder.getAddress());
                        ps.setInt(11, salesOrder.getSaleType());
                        ps.setInt(12, salesOrder.getStatus());
                        ps.setString(13, salesOrder.getCreateBy());
                        ps.setString(14, salesOrder.getSource());
                        ps.setInt(15, salesOrder.getPayMethod());
                        ps.setInt(16, salesOrder.getPayStatus());
                        ps.setLong(17, salesOrder.getPayTime());
                        ps.setBigDecimal(18, salesOrder.getPayAmount());
                        ps.setString(19, salesOrder.getOrderDate());
                        ps.setLong(20, System.currentTimeMillis() / 1000);
                        ps.setString(21, salesOrder.getSellerMemo());
                        ps.setInt(22, salesOrder.getSalesManId());
                        return ps;
                    }
                }, keyHolder);

                salesOrderId = keyHolder.getKey().longValue();


            } else {
                //修改
                jdbcTemplate.update(insertSQL.toString(), salesOrder.getOrderNum(), salesOrder.getGoodsTotalAmount(), salesOrder.getShippingFee(), salesOrder.getTotalAmount(), salesOrder.getContactPerson(), salesOrder.getContactMobile(), salesOrder.getProvince(),
                        salesOrder.getCity(), salesOrder.getArea(), salesOrder.getAddress(), salesOrder.getSaleType(), salesOrder.getStatus(), salesOrder.getCreateBy(), salesOrder.getSource(), salesOrder.getPayMethod(), salesOrder.getPayStatus(), salesOrder.getPayTime(), salesOrder.getPayAmount(),
                        salesOrder.getSellerMemo(), salesOrder.getId());
                //删除订单明细
                jdbcTemplate.update("DELETE FROM " + Tables.SalesOrderItem + " WHERE orderId=?", salesOrder.getId());
            }


            //添加订单明细
            String itemSQL = "INSERT INTO " + Tables.SalesOrderItem + " (orderId,itemAmount,goodsId,goodsTitle,goodsNumber,goodsImage,skuInfo,specId,specNumber,price,quantity) VALUE (?,?,?,?,?,?,?,?,?,?,?)";

            for (ErpSalesOrderItemEntity item : salesOrder.getItems()) {
                //商品规格总价
                double itemAmount = item.getPrice().doubleValue() * item.getQuantity();

                jdbcTemplate.update(itemSQL, salesOrderId, itemAmount
                        , item.getGoodsId() == null ? 0 : item.getGoodsId()
                        , item.getGoodsTitle()
                        , StringUtils.isEmpty(item.getGoodsNumber()) ? "" : item.getGoodsNumber()
                        , StringUtils.isEmpty(item.getGoodsImage()) ? "" : item.getGoodsImage()
                        , StringUtils.isEmpty(item.getSkuInfo()) ? "" : item.getSkuInfo()
                        , item.getSpecId() == null ? 0 : item.getSpecId()
                        , StringUtils.isEmpty(item.getSpecNumber()) ? "" : item.getSpecNumber()
                        , item.getPrice(), item.getQuantity());
            }


            return new ResultVo<>(EnumResultVo.SUCCESS, "成功");
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return new ResultVo<>(EnumResultVo.Fail, "添加订单失败：" + e.getMessage());
        }
    }

    /**
     * 更新物流信息
     * @param orderId
     * @param logisticsCode
     * @param logisticsCompany
     * @param logisticsCompanyCode
     * @param logisticsImg
     */
    public void updateLogisticsStatus(Long orderId, String logisticsCode, String logisticsCompany, String logisticsCompanyCode, String logisticsImg) {
        try {
            jdbcTemplate.update("UPDATE " + Tables.SalesOrder + " SET logisticsStatus=1,logisticsCompany=?,logisticsCompanyCode=?,logisticsCode=?,logisticsImg=?,modifyOn=? WHERE id=?",
                    logisticsCompany, logisticsCompanyCode, logisticsCode, logisticsImg, System.currentTimeMillis() / 1000,
                    orderId);
        }catch (Exception e){
            throw  e;
        }
    }

    public ResultVo<Integer> sendOrder(Long orderId) {
        try{
            String detailSQL = "SELECT o.* FROM " + Tables.SalesOrder + " AS o  WHERE o.id=?";
            ErpSalesOrderEntity order = jdbcTemplate.queryForObject(detailSQL, new BeanPropertyRowMapper<>(ErpSalesOrderDetailVo.class), orderId);
            if(order.getLogisticsStatus().intValue() == 0 || StringUtils.isEmpty(order.getLogisticsCode()))  return new ResultVo<>(EnumResultVo.DataError,"未打单，请打单");
            if(order.getDeliveredStatus().intValue() == 1)  return new ResultVo<>(EnumResultVo.DataError,"订单已经发货，不能再次发货");
            if(order.getStatus().intValue() != EnumErpOrderStatus.WaitSend.getIndex())  return new ResultVo<>(EnumResultVo.DataError,"订单状态不是待发货状态");
        }
        catch (Exception e){
            return new ResultVo<>(EnumResultVo.DataError,"没找到订单");
        }

        try {
            jdbcTemplate.update("UPDATE " + Tables.SalesOrder + " SET deliveredStatus=1,deliveredTime=?,status=?,modifyOn=? WHERE id=?",
                    System.currentTimeMillis() / 1000 ,EnumErpOrderStatus.Delivered.getIndex(), System.currentTimeMillis() / 1000,
                    orderId);
            return new ResultVo<>(EnumResultVo.SUCCESS,"");
        }catch (Exception e){
//            throw  e;
            return new ResultVo<>(EnumResultVo.SystemException,e.getMessage());
        }
    }


    public ResultVo<Integer> sendOrder(OrderSendReq orderSendReq) {
        try{
            String detailSQL = "SELECT o.* FROM " + Tables.SalesOrder + " AS o  WHERE o.id=?";
            ErpSalesOrderEntity order = jdbcTemplate.queryForObject(detailSQL, new BeanPropertyRowMapper<>(ErpSalesOrderDetailVo.class), orderSendReq.getOrderId());

//            if(order.getLogisticsStatus().intValue() == 0 || StringUtils.isEmpty(order.getLogisticsCode()))  return new ResultVo<>(EnumResultVo.DataError,"未打单，请打单");

            if(order.getDeliveredStatus().intValue() == 1)  return new ResultVo<>(EnumResultVo.DataError,"订单已经发货，不能再次发货");
            if(order.getStatus().intValue() != EnumErpOrderStatus.WaitSend.getIndex())  return new ResultVo<>(EnumResultVo.DataError,"订单状态不是待发货状态");

            if(orderSendReq.getLogisticsType() == 0){
                //快递发货,更新订单信息

            }

        }
        catch (Exception e){
            return new ResultVo<>(EnumResultVo.DataError,"没找到订单");
        }

        try {
            jdbcTemplate.update("UPDATE " + Tables.SalesOrder + " SET deliveredStatus=1,deliveredTime=?,status=?,modifyOn=?," +
                            "contactPerson=?,contactMobile=?,address=?,logisticsCompany=?,logisticsCompanyCode=?,logisticsCode=?,sellerMemo=?,logisticsType=? WHERE id=?",
                    System.currentTimeMillis() / 1000 ,EnumErpOrderStatus.Delivered.getIndex(), System.currentTimeMillis() / 1000,
                    orderSendReq.getContactPerson(),orderSendReq.getMobile(),orderSendReq.getAddress(),orderSendReq.getLogisticsCompany(),orderSendReq.getLogisticsCompanyCode(),
                    orderSendReq.getLogisticsCode(),orderSendReq.getSellerMemo(),orderSendReq.getLogisticsType(),
                    orderSendReq.getOrderId());
            return new ResultVo<>(EnumResultVo.SUCCESS,"");
        }catch (Exception e){
//            throw  e;
            return new ResultVo<>(EnumResultVo.SystemException,e.getMessage());
        }
    }

    public ResultVo<Integer> cancelOrder(Long orderId) {
        try{
            String detailSQL = "SELECT o.* FROM " + Tables.SalesOrder + " AS o  WHERE o.id=?";
            ErpSalesOrderEntity order = jdbcTemplate.queryForObject(detailSQL, new BeanPropertyRowMapper<>(ErpSalesOrderDetailVo.class), orderId);

//            if(order.getLogisticsStatus().intValue() == 0 || StringUtils.isEmpty(order.getLogisticsCode()))  return new ResultVo<>(EnumResultVo.DataError,"未打单，请打单");

//            if(order.getDeliveredStatus().intValue() == 1)  return new ResultVo<>(EnumResultVo.DataError,"订单已经发货，不能取消");
            if(order.getStatus().intValue() != EnumErpOrderStatus.WaitSend.getIndex())  return new ResultVo<>(EnumResultVo.DataError,"订单状态不是待发货状态，不能取消");

            //取消订单
            String sql = "UPDATE "+Tables.SalesOrder+" SET status=-1,deliveredStatus=0,logisticsStatus=0,logisticsCompany='',logisticsCompanyCode='',logisticsCode='',logisticsImg='' WHERE id=?";
            jdbcTemplate.update(sql,orderId);
            return new ResultVo<>(EnumResultVo.SUCCESS,"");
        }
        catch (Exception e){
            return new ResultVo<>(EnumResultVo.DataError,"没找到订单");
        }

    }


    public ResultVo<Integer> refundOrder(Long orderId) {
        try{
            String detailSQL = "SELECT o.* FROM " + Tables.SalesOrder + " AS o  WHERE o.id=?";
            ErpSalesOrderEntity order = jdbcTemplate.queryForObject(detailSQL, new BeanPropertyRowMapper<>(ErpSalesOrderDetailVo.class), orderId);

//            if(order.getLogisticsStatus().intValue() == 0 || StringUtils.isEmpty(order.getLogisticsCode()))  return new ResultVo<>(EnumResultVo.DataError,"未打单，请打单");

//            if(order.getDeliveredStatus().intValue() == 1)  return new ResultVo<>(EnumResultVo.DataError,"订单已经发货，不能取消");
            if(order.getStatus().intValue() != EnumErpOrderStatus.Delivered.getIndex())  return new ResultVo<>(EnumResultVo.DataError,"订单状态不是已发货状态，不能取消");

            //取消订单
            String sql = "UPDATE "+Tables.SalesOrder+" SET status=6 WHERE id=?";
            jdbcTemplate.update(sql,orderId);
            return new ResultVo<>(EnumResultVo.SUCCESS,"");
        }
        catch (Exception e){
            return new ResultVo<>(EnumResultVo.DataError,"没找到订单");
        }

    }
}
